package cn.com.code.design.event;

import cn.com.code.design.LotteryResult;
import cn.com.code.design.event.listener.EventListener;

import java.lang.annotation.ElementType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 事件处理类
 *
 * @author zhengpei
 * @date 2021/11/2
 */
public class EventManager {

  Map<Enum<EventType>, List<EventListener>> listeners = new HashMap<>();

  public EventManager(Enum<EventType>... operations) {
    for (Enum<EventType> operation : operations) {
      this.listeners.put(operation, new ArrayList<>());
    }
  }

  public enum EventType {
    MQ, Message
  }

  /***
   * 订阅
   * @param eventType 事件类型
   * @param listener 监听
   */
  public void subscribe(Enum<EventType> eventType, EventListener listener) {
    List<EventListener> users = listeners.get(eventType);
    users.add(listener);
  }

  /**
   * 取消订阅
   *
   * @param eventTyp 事件类型
   * @param listener 监听
   */
  public void unSubScribe(Enum<EventType> eventTyp, EventListener listener) {
    List<EventListener> users = listeners.get(eventTyp);
    users.remove(listener);
  }

  /**
   * 通知
   * @param eventTyp 事件类型
   * @param result 结果
   */
  public void notify(Enum<EventType> eventTyp, LotteryResult result) {
    List<EventListener> users = listeners.get(eventTyp);
    for (EventListener listener : users) {
      listener.doEvent(result);
    }
  }

}
